﻿// <copyright file="Macro.cs" company="Joe Chung">
// Copyright © 2008 by Joe Chung.
// </copyright>
namespace NScheme
{
    using System;

    public sealed class Macro : NScheme.Closure
    {
        public Macro(object parms, object body, Environment env)
            : base(parms, body, env)
        {
        }

        public Pair expand(Scheme interpreter, Pair oldPair, object args)
        {
            object expansion = apply(interpreter, args);
            if (expansion is Pair)
            {
                oldPair.first = ((Pair)expansion).first;
                oldPair.rest = ((Pair)expansion).rest;
            }
            else
            {
                oldPair.first = "begin";
                oldPair.rest = cons(expansion, null);
            }

            return oldPair;
        }

        public static object macroExpand(Scheme interpreter, object x)
        {
            if (!(x is Pair))
            {
                return x;
            }

            object fn = interpreter.eval(first(x), interpreter.globalEnvironment);
            return !(fn is Macro) ? x : ((Macro)fn).expand(interpreter, (Pair)x, rest(x));
        }
    }
}